//
//  XWClassRoomManager.swift
//  XWClassroom
//
//  Created by xianquan on 2023/11/27.
//

import UIKit
import Alamofire
import HandyJSON

@objc public protocol UserInfoReloadProtocol {
    func reloadAfterUpdateUserInfo()
}

@objc public protocol NetworkStatusChangeProtocol {
    func networkStatusChanged(manager: XWClassRoomManager)
}

@objc public protocol ChangeLanguageProtocol {
    func updateLanguare()
}

@objcMembers public class XWClassRoomManager: NSObject {
    
    public static let shared = XWClassRoomManager()
    
    /// 日志记录类型
    public static var logType: LogType = appEnvironment == .product ? .none : .file
    
    
    private var reachability: NetworkReachabilityManager?
    
    /// 登录后刷新页面，首页，我的页，以及需要刷新的页面需要遵守UserInfoReloadProtocol，并实现方法
    public var reloadDelegates: NSHashTable<UserInfoReloadProtocol> = .weakObjects()
    
    public var networkDelegates: NSHashTable<NetworkStatusChangeProtocol> = .weakObjects()
    
    public var languageDelegates: NSHashTable<ChangeLanguageProtocol> = .weakObjects()
    
    public var networkStatus: NetworkReachabilityManager.NetworkReachabilityStatus = .notReachable
    
    public var isNetworkError: Bool {
        return networkStatus == .notReachable || networkStatus == .unknown
    }
    
    private override init(){
        super.init()
        networkListener()
        
        XWDeviceHelper.loadDeviceName()
        
        InstallUncaughtExceptionHandler()
    }
    
    // MARK: network
    func networkListener(){
        reachability = NetworkReachabilityManager()
        reachability?.startListening(onUpdatePerforming: {[self] status in
//            NotificationCenter.default.post(name: .netWorkChanged, object: status)
            networkStatus = status
            for delegate in networkDelegates.allObjects {
                delegate.networkStatusChanged(manager: self)
            }
            switch status {
            case .unknown:
                XWLog(value: "网络未知")
            case .notReachable:
                XWLog(value: "网络未连接")
            case .reachable(.ethernetOrWiFi):
                XWLog(value: "wifi连接")
            case .reachable(.cellular):
                XWLog(value: "蜂窝网络")
            }
        })
    }
    
    public func refreshAllAfterLogin() {
        
        for delegate in reloadDelegates.allObjects {
            delegate.reloadAfterUpdateUserInfo()
        }
    }
    
    public func refreshAllAfterChangeLanguage() {
        for delegate in languageDelegates.allObjects {
            delegate.updateLanguare()
        }
    }
}

public  let cccccclogType : XWClassRoomManager.LogType = .none

extension XWClassRoomManager{
    
    @objc(XWClassRoomLogType) public enum LogType: Int{
        /// 不记录
        case none
        /// 只在控制台输出
        case console
        /// 在控制台输出同时保存到文件
        case file
    }
    

}
